import type { UserInfo, LoginInfo } from '/#/store';
import { defineStore } from 'pinia';
import { store } from '/@/store';
import { RoleEnum } from '/@/common/enums/sysEnum';
import { PageEnum } from '/@/common/enums/sysEnum';
import { data_dict, info_oauth2_tenant_id } from '/@/common/constant/cacheConst';
import { getLoginInfo, doLoginByPhone, doLogout } from '/@/api/common/sys';
import { router } from '/@/router';
import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage';
import { isOAuth2AppEnv } from "/@/views/system/login/pc1/useLogin";
import { getToken } from '/@/common/util/auth';
import { getAuthCache, setAuthCache, removeAuthCache } from '/@/common/util/localCache';

import { token_key, tenant_id, user_info_key } from '/@/common/constant/cacheConst';
import { createLocalStorage } from '/@/common/util/localCache';
const cls = createLocalStorage();

interface dictType {
  [key: string]: any;
}
interface UserState {
  userInfo: Nullable<UserInfo>;
  token?: string;
  roleList: RoleEnum[];
  dictItems?: dictType | null;
  sessionTimeout?: boolean;
  tenantid?: string | number;
  loginInfo?: Nullable<LoginInfo>;
  teamList: [];
  orgCode?: string;
  orgName?: string;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): UserState => ({
    userInfo: null,   // 用户信息
    token: undefined,
    roleList: [],     // 角色列表
    dictItems: null,  // 字典
    sessionTimeout: false,  // session过期时间
    tenantid: '',           //租户id
    loginInfo: null,        //登录返回信息
    teamList: [],           //班组绩效兼职列表及默认值
    orgCode: undefined,
    orgName: undefined,
  }),
  getters: {
    getOrgCode() {
      return this.orgCode;
    },
    getOrgName() {
      return this.orgName;
    },
    getTeamList() {
      return this.teamList;
    },
    getUserInfo() {
      return this.userInfo || {};
    },
    getLoginInfo() {
      return this.loginInfo || {};
    },
    getToken(): string {
      return this.token || getToken();
    },
    getAllDictItems() {
      return this.dictItems;
    },
    getRoleList(): RoleEnum[] {
      return this.roleList.length > 0 ? this.roleList : [];
    },
    getSessionTimeout(): boolean {
      return !!this.sessionTimeout;
    },
    getTenant(): string | number {
      return this.tenantid || '';
    },
  },
  actions: {
    setTeamOrgCode(info: string | undefined) {
      this.orgCode = info ? info : '';
    },
    setTeamOrgName(info: string | undefined) {
      this.orgName = info ? info : '';
    },
    setTeamList(info: [] | undefined) {
      this.teamList = info ? info : [];
    },
    setToken(info: string | undefined) {
      this.token = info ? info : '';
      cls.set(token_key, info);
    },
    setRoleList(roleList: RoleEnum[]) {
      this.roleList = roleList;
    },
    setUserInfo(info: UserInfo | null) {
      this.userInfo = info;
      setAuthCache(user_info_key, info);
    },
    setLoginInfo(info: LoginInfo | null) {
      this.loginInfo = info;
      setAuthCache(user_info_key, info);
    },
    setAllDictItems(dictItems) {
      this.dictItems = dictItems;
      setAuthCache(data_dict, dictItems);
    },
    setTenant(id) {
      this.tenantid = id;
      setAuthCache(tenant_id, id);
    },
    setSessionTimeout(flag: boolean) {
      this.sessionTimeout = flag;
    },
    resetState() {
      this.userInfo = null;
      this.dictItems = null;
      this.token = '';
      this.roleList = [];
      this.sessionTimeout = false;
    },
    /**
     * 登录事件
     */
    async loginNew(params) {
      const data = await getLoginInfo(params);
      this.afterLogin(data);
      return data;
    },
    /**
     * 手机号登录
     * @param params
     */
    async phoneLogin(params) {
      const data = await doLoginByPhone(params);
      this.afterLogin(data);
      return data;
    },
    /**
     * 登录成功，路由跳转
     */
    async afterLogin(data) {
      const { token, userInfo } = data;
      //设置用户信息
      await this.setLoginInfo({ ...data, isLogin: true });
      this.setToken(token);
      this.setTenant(userInfo.tenantId);
      this.setUserInfo(userInfo);
      //路由跳转
      let redirect = router.currentRoute.value?.query?.redirect as string;
      //需要重定向则直接跳转 否则首页
      await router.replace(redirect ? redirect : '/');
    },
    /**
     * 扫码登录事件
     */
    async qrCodeLogin(params?) {
      console.log('二维码登录中....');
    },
    /**
     * 登录事件
     */
    async ThirdLogin(params?) {
      console.log('三方登录中....');
    },
    /**
     * 退出登录
     */
    async logout(goLogin = false) {
      if (this.getToken) {
        try {
          await doLogout();
        } catch {
          console.log('注销Token失败');
        }
      }
      this.setToken('');
      setAuthCache(token_key, null);
      this.setSessionTimeout(false);
      this.setUserInfo(null);
      this.setLoginInfo(null);
      this.setTenant(null);
      //退出登录后会提示「Token时效，请重新登录」
      setTimeout(() => {
        this.setAllDictItems(null);
      }, 1e3);
      //退出登录的时候需要用的应用id
      // debugger
      if (isOAuth2AppEnv()) {
        let tenantId = getAuthCache(info_oauth2_tenant_id);
        removeAuthCache(info_oauth2_tenant_id);
        goLogin && await router.push({ name: "Login", query: { tenantId: tenantId } })
      } else {
        // 修复登录成功后，没有正确重定向的问题
        goLogin && (await router.push({
          path: PageEnum.BASE_LOGIN,
          query: {
            // 传入当前的路由，登录成功后跳转到当前路由
            redirect: router.currentRoute.value.fullPath,
          }
        }));
      }
    },
    /**
     * 退出询问
     */
    confirmLoginOut() {
      const { createConfirm } = useMessage();
      const { t } = useI18n();
      createConfirm({
        iconType: 'warning',
        title: t('sys.app.logoutTip'),
        content: t('sys.app.logoutMessage'),
        onOk: async () => {
          await this.logout(true);
        },
      });
    },
  },
});

// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useUserStore(store);
}
